import curses

from ui.constants import *

class Input:

    def __init__(self, title: str, length: int, app_title: str="", description: str=""):
        self.title          = title
        self.length         = length
        self.app_title      = app_title
        self.description    = description
        self.query          = ""

    def get_desc_lines(self):
        if self.description: return self.description.split('\n')
        else: return []

    def draw_description(self, screen, y, x):
        desc_lines = self.get_desc_lines()
        for line in desc_lines:
            line_name = str(line)

            screen.attron(curses.A_ITALIC)
            screen.addstr(y, x, line_name)
            screen.attroff(curses.A_ITALIC)
            y += 1

    def draw_title(self, screen):
        y, x = 0, 0 # start point
        _, max_x = screen.getmaxyx()

        curses.init_pair(5, -1, curses.COLOR_BLUE)
        bluebg = curses.color_pair(5)

        self.clear_line(screen, y, max_x, bluebg)

        title = " " + self.app_title
        title = title + (' ' * (max_x-len(title)))

        screen.addstr(y, x, title, bluebg)

        return y+1

    def clear_line(self, screen, y, l, attr=None):
        for i in range(l): screen.addstr(y, i, ' ', attr)

    def draw(self, screen):
        screen.erase()

        y, x = 0, 1 # start point
        
        y = self.draw_title(screen)

        curses.init_pair(1, curses.COLOR_GREEN, -1)

        curses.echo() 
        screen.addstr(y, x, self.title + self.query, curses.color_pair(1))
        self.draw_description(screen, y+2, x)

        screen.refresh()

        return y, len(self.title)+1

    def _loop(self, screen):
        while True:
            y, x = self.draw(screen)
            screen.move(y, x + len(self.query))

            char = screen.get_wch()
            char_code = char
            if type(char) is str: 
                char_code = ord(char)

            if char_code in KEYS_ENTER:
                return self.query
            elif char in KEYS_BACKSPACE:
                self.query = self.query[:-1]
            else:
                self.query += char

    def init_curses(self):
        # use the default colors of the terminal
        curses.use_default_colors()

        curses.init_pair(2, curses.COLOR_MAGENTA, -1)

        curses.curs_set(1)

        curses.initscr()

    def _start(self, screen):
        self.init_curses()
        screen.idlok(False)
        screen.idcok(False)
        return self._loop(screen)

    def start(self):
        return curses.wrapper(self._start)

def ninput(title: str, length: int, app_title: str="", description: str=""):
    inp = Input(title, length, app_title, description)
    
    return inp.start()

if __name__ == "__main__":
    inp = ninput("Your name: ", 100, "Test input", "Woops!") 
    print(inp)



